import { Injectable } from '@angular/core';
import { Observable } from "rxjs";

@Injectable()
export class WebSocketService {

  ws: WebSocket;

  constructor() { }

  //这个是创建一个websocket
  createObservableSocket(url:string): Observable<any> {
    this.ws = new WebSocket(url);
    return new Observable(  //新建一个流。什么时候发射下个元素(流)？什么时候抛出一个异常？什么时候发射结束信号？
      observer => {
        this.ws.onmessage = (event) => observer.next(event.data);//1
        this.ws.onerror = (event) => observer.error(event);//2
        this.ws.onclose = (event) => observer.complete();//3
      }
    )
  }

  //第二个方法。向服务器发送一个消息。
  sendMessage(message: string) {
    this.ws.send(message);
  }
}
